package edu.tjhsst.androidIntranet.news;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import android.content.Context;
import android.content.res.AssetManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import edu.tjhsst.androidIntranet.PageLoader;
import edu.tjhsst.androidIntranet.db.IntranetDbAdapter;
import edu.tjhsst.androidIntranet.period8.EighthLoaderThread;

public class NewsLoaderThread extends Thread {

	private static final boolean readFromWeb = true;
	private static final String TAG = "NewsLoaderThread";
	Handler h;
	IntranetDbAdapter.NewsDbAdapter nDbA;
	Context c;

	public NewsLoaderThread(Handler h, Context c) {
		this.h=h;
		this.c=c;
		nDbA = IntranetDbAdapter.getNewsDbAdapter(c);
	}

	public void run() {
		loadNews(h);

		Bundle c = new Bundle();
		c.putBoolean("IsUpdateComplete", true);
		Message n = new Message();
		n.setData(c);
		h.sendMessage(n);

		//loadOldNews(h);
	}

	private static Pattern newsPattern = Pattern.compile(
			//ID:
			"<a name=\"newspost(\\d+?)\"></a>." +
			"<div class=\"newsoptions\">." +
			"<a href=\"https://iodine.tjhsst.edu/news/shade/\\1\" onclick=\"return doNewsShade\\(\\1\\)\" id=\"shadelink_\\1\">Collapse</a> - ." +
			" 	<a href=\"https://iodine.tjhsst.edu/news/read/\\1\">Mark read</a>." +
			" </div>." +
			//Title:
			"<div class=\"newstitle\" ondblclick=\"doNewsShade\\(\\1\\)\">(.+?)</div>." +
			"<div class=\"newsitem\">." +
			"<div class=\"newsgroups\">." +
			//Poster & Date:
			" Posted by (.+?) on (.+?) at\\s+(.+?) to .+?[.]</div>." +
			//Content:
			"<div id=\"newsitem_\\1\">(.+?)\\s*</div>"
			,Pattern.DOTALL);

	private void loadNews(Handler postTo) {
		StringBuffer page=null;
		if(readFromWeb) {
			PageLoader.downloadPage("");
			page = PageLoader.getPage();
		} else {
			page = new StringBuffer();
			AssetManager am = c.getAssets();
			BufferedReader br = null;
			try {
				br = new BufferedReader(new InputStreamReader(am.open("i2.htm")));
			} catch (IOException e) {
				e.printStackTrace();
			}
			String line;
			try {
				while ((line = br.readLine()) != null) {
					page.append(line);
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		Matcher matcher = newsPattern.matcher(page);
		Log.d(TAG, "Matching");
		boolean moreInfo = true;
		while (matcher.find()&&moreInfo) {
			String[] dates = matcher.group(4).split("[,\\s]+");
			String[] times = matcher.group(5).split("[: ]");
			Date postedAt = new GregorianCalendar(Integer.parseInt(dates[3]), getMonthFromString(dates[1]), Integer.parseInt(dates[2]), Integer.parseInt(times[0])+(times[2].equals("AM")?0:12), Integer.parseInt(times[1]), 0).getTime();
			moreInfo=postNews(h, Integer.parseInt(matcher.group(1)), matcher.group(2), matcher.group(6), matcher.group(3), postedAt, false);
		}
	}

	private int getMonthFromString(String month) {
		if(month.equals("January"))
			return 0;
		else if(month.equals("February"))
			return 1;
		else if(month.equals("March"))
			return 2;
		else if(month.equals("April"))
			return 3;
		else if(month.equals("May"))
			return 4;
		else if(month.equals("June"))
			return 5;
		else if(month.equals("July"))
			return 6;
		else if(month.equals("August"))
			return 7;
		else if(month.equals("September"))
			return 8;
		else if(month.equals("October"))
			return 9;
		else if(month.equals("November"))
			return 10;
		else if(month.equals("December"))
			return 11;
		else
			return -1;
	}

	private void loadOldNews(Handler postTo) {
		//PageLoader.downloadPage("news/all");
		StringBuffer page = PageLoader.getPage();
		int identifier = 0;
		String title = null;
		String content = null;
		String poster = null;
		Date datePosted = null;
		boolean read = false;

		//TODO: More parsing!!

		postNews(postTo, identifier, title, content, poster, datePosted, read);
	}

	/**
	 * If the news entry is already in the database, this returns false and exits. Otherwise, it puts the entry in the database and returns true
	 * 
	 * @param postTo
	 * @param identifier
	 * @param title
	 * @param content
	 * @param poster
	 * @param datePosted
	 * @param read
	 */
	private boolean postNews(Handler postTo, final int identifier, final String title, final String content, final String poster, final Date datePosted, final boolean read) {
		//Log.d(TAG, "Null?: "+(nDbA==null));
		Log.d(TAG, "ID: "+identifier);
		Log.d(TAG, "Title: "+title);
		Log.d(TAG, "Content:"+content);
		Log.d(TAG, "Poster: "+poster);
		//Uh oh! I'm using a deprecated method!
		Log.d(TAG, "Date Posted: "+datePosted.toGMTString());
		Log.d(TAG, "Read?: "+read);
		if(nDbA.containsEntry(identifier)) {
			return false;
		} else {
			NewsEntry ne = new NewsEntry(identifier, title, content, poster, datePosted, read);
			Bundle b = new Bundle();
			b.putSerializable("NewsEntry", ne);
			Message m = new Message();
			m.setData(b);
			h.sendMessage(m);

			return true;
		}
	}



}
